/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.routeStation.web;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.web.business.routeStation.RouteStationRestApi;
import org.opsli.api.wrapper.business.patrolStation.PatrolStationModel;
import org.opsli.api.wrapper.business.routeStation.RouteStationModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.CoordinatesConvertUtil;
import org.opsli.modulars.business.app.web.MapCordinatesVo;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.patrolRecordEXCEL.entity.PatrolRecord;
import org.opsli.modulars.business.routeStation.service.impl.RouteStationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

import org.opsli.modulars.business.routeStation.entity.RouteStation;
import org.opsli.modulars.business.routeStation.service.IRouteStationService;

/**
 * 基准线路点位 Controller
 *
 * @author zk
 * @date 2021-09-17 15:22:05
 */
@Api(tags = RouteStationRestApi.TITLE)
@Slf4j
@ApiRestController("/business/routeStation")
public class RouteStationRestController extends BaseRestController<RouteStation, RouteStationModel, IRouteStationService>
        implements RouteStationRestApi {


    /**
     * 基准线路点位 查一条
     *
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "获得单条基准线路点位", notes = "获得单条基准线路点位 - ID")
    @Override
    public ResultVo<RouteStationModel> get(RouteStationModel model) {
        // 如果系统内部调用 则直接查数据库
        if (model != null && model.getIzApi() != null && model.getIzApi()) {
            model = IService.get(model);
        }
        return ResultVo.success(model);
    }

    @Autowired
    RouteStationServiceImpl rs;

    @Override
    public ResultVo<List<Map>> findLast(String routeid) {
        String devid = UserUtil.getSysUser().getCompanyId();//当前公司ID
        List list = new ArrayList();
        if (devid.equals("41006")) {
            Map map = new HashMap();
            map.put("devid", devid);
            list.add(map);
            List l2 = new ArrayList();
            if (routeid.equals("1506506467359559682") || routeid.equals("1528987038416699393")) {
                List<RouteStation> l = rs.findAnZeList(routeid);
                for (int i = 0; i < l.size(); i++) {
                    Map m = new HashMap();
                    RouteStation r = l.get(i);
                    String longitude = r.getLongitude();
                    String dimension = r.getDimension();

                    m.put("lt", longitude);
                    m.put("ln", dimension);
                    l2.add(m);
                    if (longitude.equals("0") && dimension.equals("0")) {
                        List l3 = new ArrayList();
                        for (int a = 0; a < l2.size() - 1; a++) {
                            l3.add(l2.get(a));
                        }
                        list.add(l3);
                        l2.clear();
                    }
                }
            } else {
                List<RouteStation> l = rs.findAnZeList(routeid);
                for (int i = 0; i < l.size(); i++) {
                    Map m = new HashMap();
                    RouteStation r = l.get(i);
                    String longitude = r.getLongitude();
                    String dimension = r.getDimension();

                    m.put("lt", longitude);
                    m.put("ln", dimension);
                    l2.add(m);
                }
                List l3 = new ArrayList();
                for (int a = 0; a < l2.size(); a++) {
                    l3.add(l2.get(a));
                }
                list.add(l3);
            }

        } else {
            List<RouteStation> stations = IService.findList(routeid);
            if (stations != null && stations.size() > 0) {
                for (RouteStation station : stations) {
                    Map map = new HashMap();
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(station.getLongitude()));
                    cordinatesVo.setLat(new BigDecimal(station.getDimension()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("lt", cordinatesVo.getLon());
                    map.put("ln", cordinatesVo.getLat());
                    map.put("lo", station.getLocation());
                    list.add(map);
                }
            }
        }
        return ResultVo.success(list);
    }

    /**
     * 基准线路点位 查询分页
     *
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultVo
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @Override
    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryBuilder<RouteStation> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        Page<RouteStation, RouteStationModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }

    /**
     * 基准线路点位 新增
     *
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "新增基准线路点位数据", notes = "新增基准线路点位数据")
    @EnableLog
    @Override
    public ResultVo<?> insert(RouteStationModel model) {
        try {
            MapCordinatesVo cordinatesVo = new MapCordinatesVo();
            cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
            cordinatesVo.setLat(new BigDecimal(model.getDimension()));
            cordinatesVo = CoordinatesConvertUtil.gd_decrypt(cordinatesVo);
            model.setLongitude(cordinatesVo.getLon().toString());
            model.setDimension(cordinatesVo.getLat().toString());
        } catch (Exception e) {

        }
        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增基准线路点位成功");
    }

    /**
     * 查询自定义路线
     *
     * @param routeid
     * @return
     */
    @RequestMapping(value = "/findCustomRoute", method = RequestMethod.POST)
    public ResultVo<List<Map>> findCustomRoute(String routeid) {
        List list = new ArrayList();
        List<RouteStation> l = rs.findCustomList(routeid);
        String flag = null;
        for (int i = 0; i < l.size(); i++) {
            flag = l.get(i).getFlag();
            if (StringUtils.isNotBlank(flag)) {
                break;
            }
        }
        if (StringUtils.isNotBlank(flag)) {
            Map map = new HashMap();
            map.put("local", "zdy");
            list.add(map);
            TreeSet tr = new TreeSet();
            for (int a = 0; a < l.size(); a++) {
                RouteStation r = l.get(a);
                String fl = r.getFlag();
                if (StringUtils.isNotBlank(fl)) {
                    tr.add(fl);
                }
            }
            for (Iterator iter = tr.iterator(); iter.hasNext(); ) {
                String flagName = (String) iter.next();
                List l1 = new ArrayList();
                for (int b = 0; b < l.size(); b++) {
                    Map m = new HashMap();
                    RouteStation r = l.get(b);
                    String longitude = r.getLongitude();
                    String dimension = r.getDimension();
                    String b1Name = r.getFlag();
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(longitude));
                    cordinatesVo.setLat(new BigDecimal(dimension));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    m.put("lt", cordinatesVo.getLon());
                    m.put("ln", cordinatesVo.getLat());
                    if (StringUtils.isNotBlank(b1Name)) {
                        m.put("flag", b1Name);
                        if (b1Name.equals(flagName)) {
                            l1.add(m);
                        }
                    }
                }
                list.add(l1);
            }
        }
        return ResultVo.success(list);
    }

    /**
     * 查询非自定义路线
     *
     * @param routeid
     * @return
     */
    @RequestMapping(value = "/findLocalRoute", method = RequestMethod.POST)
    public ResultVo<List<Map>> findLocalRoute(String routeid) {
        List list = new ArrayList();
        List<RouteStation> l = rs.findCustomList(routeid);
        for (int b = 0; b < l.size(); b++) {
            Map m = new HashMap();
            RouteStation r = l.get(b);
            String longitude = r.getLongitude();
            String dimension = r.getDimension();
            String b1Name = r.getFlag();
            MapCordinatesVo cordinatesVo = new MapCordinatesVo();
            cordinatesVo.setLon(new BigDecimal(longitude));
            cordinatesVo.setLat(new BigDecimal(dimension));
            cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
            m.put("lt", cordinatesVo.getLon());
            m.put("ln", cordinatesVo.getLat());
            if (StringUtils.isBlank(b1Name)) {
                m.put("flag", "localRoute");
                list.add(m);
            }
        }
        return ResultVo.success(list);
    }

    /**
     * 查询中心点
     *
     * @return
     */
    @RequestMapping(value = "/findCenterPoint", method = RequestMethod.POST)
    public ResultVo<List<Map>> findCenterPoint() {
        List list = new ArrayList();
        String devid = UserUtil.getSysUser().getCompanyId();
        Map<String, String> map = rs.findCenterPoint(devid);
        if (map != null) {
            String lng = map.get("ln");
            String lat = map.get("lt");
            Map m = new HashMap();
            MapCordinatesVo cordinatesVo = new MapCordinatesVo();
            cordinatesVo.setLon(new BigDecimal(lat));
            cordinatesVo.setLat(new BigDecimal(lng));
            cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
            m.put("lt", cordinatesVo.getLon());
            m.put("ln", cordinatesVo.getLat());
            list.add(m);
        } else {
            String lng = "39.914714";//北京坐标
            String lat = "116.404269";
            Map m = new HashMap();
            MapCordinatesVo cordinatesVo = new MapCordinatesVo();
            cordinatesVo.setLon(new BigDecimal(lat));
            cordinatesVo.setLat(new BigDecimal(lng));
            cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
            m.put("lt", cordinatesVo.getLon());
            m.put("ln", cordinatesVo.getLat());
            list.add(m);
        }

        return ResultVo.success(list);
    }

    /**
     * 删除非自定义路线
     *
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @RequestMapping(value = "/deleteLocalRoute", method = RequestMethod.POST)
    public ResultVo<?> deleteLocalRoute(String id) {
        List l = rs.selectLocalId(id);
        for (int i = 0; i < l.size(); i++) {
            String getId = String.valueOf(l.get(i));
            rs.deleteLocalRoute(getId);
        }
        return ResultVo.success("删除成功");
    }

    /**
     * 基准路线自定义设置线路
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/insertCustom", method = RequestMethod.POST)
    public ResultVo<?> insertCustom(RouteStationModel model) {
        try {
            MapCordinatesVo cordinatesVo = new MapCordinatesVo();
            cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
            cordinatesVo.setLat(new BigDecimal(model.getDimension()));
            cordinatesVo = CoordinatesConvertUtil.gd_decrypt(cordinatesVo);
            model.setLongitude(cordinatesVo.getLon().toString());
            model.setDimension(cordinatesVo.getLat().toString());
        } catch (Exception e) {

        }
        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增基准线路点位成功");
    }

    /**
     * 基准路线自定义设置线路--删除数据库已设置好的数据
     *
     * @param flag
     * @return
     */
    @Transactional(readOnly = false)
    @RequestMapping(value = "/deleteCustom", method = RequestMethod.POST)
    public ResultVo<?> deleteCustom(String flag) {
        System.out.println("flag==" + flag);
        rs.deleteCustom(flag);
        return ResultVo.success("删除成功");
    }


    /**
     * 基准线路点位 修改
     *
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "修改基准线路点位数据", notes = "修改基准线路点位数据")
    @EnableLog
    @Override
    public ResultVo<?> update(RouteStationModel model) {
        RouteStationModel old = IService.get(model.getId());
        if (ZkUtils.isNotBlank(model.getDimension()) && ZkUtils.isNotBlank(model.getLongitude())) {
            if (!model.getDimension().equals(old.getDimension()) || !model.getLongitude().equals(old.getLongitude())) {
                MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
                cordinatesVo.setLat(new BigDecimal(model.getDimension()));
                cordinatesVo = CoordinatesConvertUtil.gd_decrypt(cordinatesVo);
                model.setLongitude(cordinatesVo.getLon().toString());
                model.setDimension(cordinatesVo.getLat().toString());
            }
        }
        // 调用修改方法
        IService.update(model);
        return ResultVo.success("修改基准线路点位成功");
    }


    /**
     * 基准线路点位 删除
     *
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除基准线路点位数据", notes = "删除基准线路点位数据")
    @EnableLog
    @Transactional(readOnly = false)
    @Override
    public ResultVo<?> del(String id) {
        IService.deleteStation(id);
        return ResultVo.success("删除基准线路点位成功");
    }

    /**
     * 基准线路点位 批量删除
     *
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除基准线路点位数据", notes = "批量删除基准线路点位数据")
    @RequiresPermissions("routestation_update")
    @EnableLog
    @Override
    public ResultVo<?> delAll(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultVo.success("批量删除基准线路点位成功");
    }


    /**
     * 基准线路点位 Excel 导出
     * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
     * <p>
     * 导出时，Token认证和方法权限认证 全部都由自定义完成
     * 因为在 导出不成功时，需要推送错误信息，
     * 前端直接走下载流，当失败时无法获得失败信息，即使前后端换一种方式后端推送二进制文件前端再次解析也是最少2倍的耗时
     * ，且如果数据量过大，前端进行渲染时直接会把浏览器卡死
     * 而直接开启socket接口推送显然是太过浪费资源了，所以目前采用Java最原始的手段
     * response 推送 javascript代码 alert 提示报错信息
     *
     * @param request  request
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @RequiresPermissionsCus("routestation_export")
    @EnableLog
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "exportExcel");
        QueryBuilder<RouteStation> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        super.excelExport(RouteStationRestApi.SUB_TITLE, queryBuilder.build(), response, method);
    }

    /**
     * 基准线路点位 Excel 导入
     * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
     *
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @RequiresPermissions("routestation_import")
    @EnableLog
    @Override
    public ResultVo<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    /**
     * 基准线路点位 Excel 下载导入模版
     * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
     *
     * @param response response
     */
    @ApiOperation(value = "导出Excel模版", notes = "导出Excel模版")
    @RequiresPermissionsCus("routestation_import")
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "importTemplate");
        super.importTemplate(RouteStationRestApi.SUB_TITLE, response, method);
    }

}